package com.ffyc.backserver.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.ffyc.backserver.common.CommonResult;
import com.ffyc.backserver.common.JWTUtil;
import com.ffyc.backserver.model.Admin;
import com.ffyc.backserver.model.Menu;
import com.ffyc.backserver.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/*   *//*允许跨域访问*//*
    @CrossOrigin("http://localhost:8080")*/
@RestController

@RequestMapping(path = "/api/login")

public class LoginController {
    @Autowired
    LoginService loginService;

    @RequestMapping(path = "login")
    public CommonResult login(@RequestBody Admin admin){
        CommonResult commonResult=null;
        try {
            Admin admin1=loginService.login(admin);
            if (admin1!=null){
                /*生成token*/
                 String token= JWTUtil.token(admin1.getId(),admin1.getAccount(),admin1.getType());
                 admin1.setToken(token);
                 commonResult=new CommonResult<Admin>(200,"登陆成功",admin1);
            }
            else {
                commonResult=new CommonResult<Admin>(201,"测试",null);
            }
        }catch (Exception e){
            e.printStackTrace();
            commonResult=new CommonResult<Admin>(500,"登陆失败",null);
        }

        return commonResult;
    }


    @GetMapping(path = "findMenu")
    public CommonResult findMenu(@RequestHeader("token") String token) {

        CommonResult commonResult = null;
        //token包含三个信息 account id type

        try {
            DecodedJWT tokenInfo = JWTUtil.getTokenInfo(token);
            Integer id= tokenInfo.getClaim("id").asInt();
            Integer type=  tokenInfo.getClaim("type").asInt();
            List<Menu>menuList=loginService.findMenu(id,type);

            commonResult = new CommonResult<List<Menu>>(200,"查找菜单成功" , menuList);
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult<List<Menu>>(500,"查找菜单失败" , null);
        }
        return commonResult;
    }



}
